//
//  FindViewController2.m
//  BuffetNews
//
//  Created by weidawei on 14-10-30.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "FindViewController2.h"
#import "TwoTableViewCell.h"
#import "SecondViewController.h"
#import "Channel.h"
#import "ChannelSearchViewController.h"
#import "visionController.h"

#import "CartoonViewController.h"
#import "visionController.h"


#import "NightModel.h"
#import "WebColor.h"
@interface FindViewController2 ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, retain) UITableView * tabler;
@property (nonatomic, retain) NSMutableArray *blockData;
@property (nonatomic, retain) NSMutableArray *modelArr;
@end

@implementation FindViewController2

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.titleArr = [NSMutableArray array];
        self.pkArr = [ NSMutableArray array];
        self.api_urlArr = [NSMutableArray array];
        self.blockData = [NSMutableArray array];
        self.modelArr= [NSMutableArray array];

        // Custom initialization
    }
    return self;
}
- (void)dealloc
{
    [_tabler release];
    [_blockData release];
    [_modelArr release];
    [_titleArr release];
    [_titleString release];
    [_api_urlArr release];
    [_block_title release];
    [_pkArr release];
    [super dealloc];
}

// 解析数据
- (void)loadingData
{
    if ([self.block_title isEqualToString:@"44"] || [self.block_title isEqualToString:@"68"] || [self.block_title isEqualToString:@"121"]) {
//        NSLog(@"视觉");
        
        for (NSDictionary *dic1 in self.sons) {
            NSMutableArray *arr1 = [dic1 objectForKey:@"sons"];
            for (NSDictionary *dic2 in arr1) {
                [self.titleArr addObject:[dic2 objectForKey:@"block_title"]];
                [self.pkArr addObject:[dic2 objectForKey:@"pk"]];
                [self.api_urlArr addObject:[dic2 objectForKey:@"api_url"]];
            }
        }
    } else {
        for (NSDictionary * dic  in self.sons) {
            //        for (NSDictionary *dic in arr) {
            [self.titleArr addObject:[dic objectForKey:@"title"]];
            [self.pkArr addObject:[dic objectForKey:@"pk"]];
            [self.api_urlArr addObject:[dic objectForKey:@"api_url"]];
        }
    }

    
    //  解析沙盒中的数据，用来后面查看某一个选项是否存在于首页选项中
    NSArray *pathrray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [pathrray objectAtIndex:0];
    NSString *filepath = [path stringByAppendingPathComponent:@"rootBlocks.plist"];
    NSDictionary *rootDictionary = [NSDictionary dictionaryWithContentsOfFile:filepath];
    self.blockData = [rootDictionary objectForKey:@"blocksData"];
    
    for ( NSString *str in self.titleArr) {
        Channel *channel = [[Channel alloc] init];
        for (NSDictionary *dic in self.blockData) {
            if ([str isEqualToString:[dic objectForKey:@"block_title"]]) {
                channel.result = YES;
                break;
            } else {
                channel.result = NO;
            }
        }
        channel.title = str;
        [self.modelArr addObject:channel];
        [channel release];
    }
    
    
}

- (void)loadingTable
{
    self.tabler = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 115)];
    self.tabler.delegate = self;
    self.tabler.dataSource = self;
    self.tabler.rowHeight = 60;
    self.tabler.alpha = 0.9;
    if ([NightModel shareInstance].open == 1) {
        self.tabler.backgroundColor = [WebColor dimGray];
    } else {
        self.tabler.backgroundColor = [UIColor whiteColor];
    }

    UIImageView *backgrnd=[[UIImageView alloc] initWithFrame:CGRectMake(0, -50, 320, 568)];
    backgrnd.contentMode=UIViewContentModeScaleAspectFit;
    
    backgrnd.image=[UIImage imageNamed:@"buff1.png"];
   
    [self.view addSubview:self.tabler];
    [self.view addSubview:backgrnd];
    [self.view bringSubviewToFront:self.tabler];
    [_tabler release];
    
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(searchAction:)];
    
}
- (void)searchAction:(UIBarButtonItem *)barbutton
{
    ChannelSearchViewController *channelVC = [[ChannelSearchViewController alloc] init];
    channelVC.bigArr = self.sons;
    channelVC.modelArr = self.modelArr;
    [self.navigationController pushViewController:channelVC animated:YES];
    [channelVC release];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
//    self.title = self.titleString;
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 20)];
    titleLabel.text = self.titleString;
    titleLabel.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = titleLabel;
    [self loadingData];
    [self loadingTable];
    // Do any additional setup after loading the view.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sons.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TwoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"1"];
    if (!cell) {
        cell = [[TwoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"1"];
    }
    cell.label1.text = self.titleArr[indexPath.row];
    cell.label1.font = [UIFont italicSystemFontOfSize:16];
    Channel *channel = self.modelArr[indexPath.row];
    if (channel.result == YES) {
        [cell.addbutton setBackgroundImage:[UIImage imageNamed:@"iconfont-duihao-2.png"] forState:UIControlStateNormal];
    } else {
        [cell.addbutton setBackgroundImage:[UIImage imageNamed:@"iconfont-circularframejiahao.png"] forState:UIControlStateNormal];
    }
    

    [cell.addbutton addTarget:self action:@selector(buttonChoose:) forControlEvents:UIControlEventTouchUpInside];
    cell.addbutton.tag = indexPath.row;
    cell.accessoryType = UITableViewCellAccessoryNone;
    
    if ([NightModel shareInstance].open == 1) {
        cell.backgroundColor = [WebColor dimGray];
        self.tabler.backgroundColor = [WebColor dimGray];
    } else {
        cell.backgroundColor = [UIColor whiteColor];
        self.tabler.backgroundColor = [UIColor whiteColor];
    }
    
    
    return cell;
}


- (void)buttonChoose:(UIButton *)button
{
    if ([button.currentBackgroundImage isEqual:[UIImage imageNamed:@"iconfont-circularframejiahao.png"]]) {
        
        Channel *channel = self.modelArr[button.tag];
        channel.result = YES;
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-duihao-2.png"] forState:UIControlStateNormal];
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"rootAdd" object:self.sons[button.tag]];
        
        
    } else{
        [button setBackgroundImage:[UIImage imageNamed:@"iconfont-circularframejiahao.png"] forState:UIControlStateNormal];
        Channel *channel = self.modelArr[button.tag];
        channel.result = NO;
        NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
        [center postNotificationName:@"rootDelete" object:self.sons[button.tag]];
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    
    
    if ([[self.sons[indexPath.row] objectForKey:@"data_type"] isEqualToString:@"episode"]) {
        CartoonViewController *carVC = [[CartoonViewController alloc] init];
        carVC.apiString = self.api_urlArr[indexPath.row];
        

        [carVC setModalTransitionStyle:UINavigationControllerHideShowBarDuration];

        
        
        
        

       

        // 2.推出
        // 参数1： 要推出的新视图控制器（VIEWcontroller）
        // 参数2. 是不是带一个动画效果


        [self presentViewController:carVC animated:YES completion:^{
            
        }];
    }

    if ([[self.sons[indexPath.row] objectForKey:@"data_type"] isEqualToString:@"photo"] ) {
        visionController *vision = [[visionController alloc] init];
        vision.visionApi = self.api_urlArr[indexPath.row];
        [vision setModalTransitionStyle:UINavigationControllerHideShowBarDuration];
        
        [self presentViewController:vision animated:YES completion:^{
            
        }];
        
    }
    
    

    SecondViewController * secon = [[SecondViewController alloc] init];
    secon.apiString = self.api_urlArr[indexPath.row];


    NSLog(@"_)_)_)_)_)_)_)_%@", secon.apiString);


//    NSLog(@"✨✨✨✨点击✨✨✨✨✨✨✨✨%@", secon.apiString);
    [secon setModalTransitionStyle:UINavigationControllerHideShowBarDuration];

    // 2.推出
    // 参数1： 要推出的新视图控制器（VIEWcontroller）
    // 参数2. 是不是带一个动画效果
    [self presentViewController:secon animated:YES completion:^{

    }];
}
- (void)viewDidAppear:(BOOL)animated
{
//    [self.tabler reloadData];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    //1. Setup the CATransform3D structure
    CATransform3D translation;
    // rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
    translation = CATransform3DMakeTranslation(0, 480, 0);
    //rotation.m34 = 1.0/ -600;
    
    
    //2. Define the initial state (Before the animation)
    cell.layer.shadowColor = [[UIColor blackColor]CGColor];
    cell.layer.shadowOffset = CGSizeMake(10, 10);
    cell.alpha = 0;
    
    cell.layer.transform = translation;
    cell.layer.anchorPoint = CGPointMake(0, 0.5);
    
    //!!!FIX for issue #1 Cell position wrong------------
    if(cell.layer.position.x != 0){
        cell.layer.position = CGPointMake(0, cell.layer.position.y);
    }
    
    //4. Define the final state (After the animation) and commit the animation
    
    [UIView beginAnimations:@"translation" context:NULL];
    [UIView setAnimationDuration:0.8];
    cell.layer.transform = CATransform3DIdentity;
    
    cell.alpha = 1;
    cell.layer.shadowOffset = CGSizeMake(0, 0);
    
    [UIView commitAnimations];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
